package com.hongtech.modules.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.google.common.collect.Lists;
import com.hongtech.common.bean.AjaxResultVo;
import com.hongtech.common.page.PageData;
import com.hongtech.framework.anno.OperateLog;
import com.hongtech.framework.anno.Permission;
import com.hongtech.modules.common.BaseController;
import com.hongtech.modules.system.dto.SysRoleDTO;
import com.hongtech.modules.system.dto.SysRoleMenuDTO;
import com.hongtech.modules.system.dto.SysUserDTO;
import com.hongtech.modules.system.dto.SysUserRoleDTO;
import com.hongtech.modules.system.entity.SysRoleEntity;
import com.hongtech.modules.system.entity.SysRoleMenuEntity;
import com.hongtech.modules.system.entity.SysUserEntity;
import com.hongtech.modules.system.entity.SysUserRoleEntity;
import com.hongtech.modules.system.service.*;
import com.hongtech.modules.system.vo.TreeMenuAccessVO;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 角色控制器
 */
@Controller
@RequestMapping("/system/sysrole")
public class RoleController extends BaseController {

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private SysUserRoleService sysUserRoleService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysMenuService sysMenuService;

    @Autowired
    private SysRoleMenuService sysRoleMenuService;

    /**
     * 跳转用户页
     */
    @Permission("system:sysrole:list")
    @RequestMapping("/list")
    public String list() {
        return "system/role/list";
    }

    /**
     * 分页查询角色
     */
    @Permission("system:sysrole:list")
    @RequestMapping("/page")
    @ResponseBody
    public AjaxResultVo page(String search, Integer offset, Integer limit) {
        LambdaQueryWrapper<SysRoleEntity> ew = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(search)) {
            ew.like(SysRoleEntity::getRoleName, search);
        }
        ew.orderByDesc(SysRoleEntity::getCreateTime);
        Map<String, Object> pageParams = getPageParam(limit, offset);
        PageData<SysRoleDTO> pages = sysRoleService.pages(pageParams, ew);
        AjaxResultVo resultVo = AjaxResultVo.success();
        resultVo.put("total", pages.getTotal());
        resultVo.put("rows", pages.getList());
        return resultVo;
    }

    /**
     * 新增角色
     */
    @Permission("system:sysrole:save")
    @RequestMapping("/add")
    public String add() {
        return "system/role/add";
    }

    /**
     * 执行新增角色
     */
    @Permission("system:sysrole:save")
    @OperateLog("创建角色")
    @RequestMapping("/doAdd")
    @ResponseBody
    public AjaxResultVo doAdd(SysRoleDTO role) {
        sysRoleService.add(role);
        return AjaxResultVo.success();
    }

    /**
     * 编辑角色
     */
    @Permission("system:sysrole:edit")
    @RequestMapping("/edit/{id}")
    public String edit(@PathVariable Long id, Model model) {
        SysRoleDTO sysRoleDTO = sysRoleService.get(id);
        model.addAttribute("sysRole", sysRoleDTO);
        return "system/role/edit";
    }

    /**
     * 执行编辑角色
     */
    @Permission("system:sysrole:edit")
    @OperateLog("编辑角色")
    @RequestMapping("/doEdit")
    @ResponseBody
    public AjaxResultVo doEdit(SysRoleDTO sysRoleDTO) {
        sysRoleService.update(sysRoleDTO);
        return AjaxResultVo.success();
    }

    /**
     * 权限
     */
    @Permission("system:sysrole:auth")
    @RequestMapping("/auth/{id}")
    public String auth(@PathVariable Long id, Model model) {
        SysRoleDTO sysRoleDTO = sysRoleService.get(id);
        if (sysRoleDTO == null) {
            throw new RuntimeException("该角色不存在");
        }
        LambdaQueryWrapper<SysRoleMenuEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysRoleMenuEntity::getRoleId, id);
        List<SysRoleMenuDTO> sysRoleList = sysRoleMenuService.list(queryWrapper);
        List<Long> menuIds = sysRoleList.stream().map(SysRoleMenuDTO::getMenuId).collect(Collectors.toList());
        List<TreeMenuAccessVO> treeMenuAccess = sysMenuService.listMenuByMenuIds(menuIds, 0L);
        model.addAttribute("sysRole", sysRoleDTO);
        model.addAttribute("treeMenuAccess", treeMenuAccess);
        return "system/role/auth";
    }

    /**
     * 权限
     */
    @Permission("system:sysrole:auth")
    @OperateLog("角色分配权限")
    @RequestMapping("/doAuth")
    @ResponseBody
    public AjaxResultVo doAuth(Long roleId, String mid) {
        sysRoleMenuService.addAuth(roleId, mid);
        return AjaxResultVo.success();
    }

    /**
     * 获取角色下的所有用户
     */
    @RequestMapping("/getUsers")
    public String getUsers(Long roleId, Model model) {
        LambdaQueryWrapper<SysUserRoleEntity> ew = new LambdaQueryWrapper<>();
        ew.eq(SysUserRoleEntity::getRoleId, roleId);
        List<SysUserRoleDTO> sysUserRoleEntities = sysUserRoleService.list(ew);
        List<Long> userIds = sysUserRoleEntities.stream().map(SysUserRoleDTO::getUserId)
                .collect(Collectors.toList());
        List<SysUserDTO> users = Lists.newArrayList();
        if (userIds.size() > 0) {
            LambdaQueryWrapper<SysUserEntity> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(SysUserEntity::getId, userIds);
            users = sysUserService.list(queryWrapper);
        }
        model.addAttribute("users", users);
        return "system/role/users";
    }

    /**
     * 获取指定角色的用户数量
     */
    @RequestMapping("/getCount")
    @ResponseBody
    public String getCount(Long roleId) {
        LambdaQueryWrapper<SysUserRoleEntity> ew = new LambdaQueryWrapper<>();
        ew.eq(SysUserRoleEntity::getRoleId, roleId);
        long count = sysUserRoleService.count(ew);
        return String.valueOf(count);
    }

    /**
     * 删除角色
     */
    @Permission("system:sysrole:remove")
    @OperateLog("删除角色")
    @RequestMapping("/delete")
    @ResponseBody
    public AjaxResultVo delete(Long id) {
        if (id == null) {
            return AjaxResultVo.error("参数错误");
        }
        if (sysRoleService.deleteRoleByIds(Lists.newArrayList(id))) {
            return AjaxResultVo.success();
        } else {
            return AjaxResultVo.error("删除失败");
        }
    }

    /**
     * 批量删除角色
     */
    @Permission("system:sysrole:remove")
    @OperateLog("批量删除角色")
    @RequestMapping("/deleteBatch")
    @ResponseBody
    public AjaxResultVo deleteBatch(@RequestParam("id[]") List<Long> ids) {
        if (ObjectUtils.isEmpty(ids)) {
            return AjaxResultVo.error("参数错误");
        }
        if (sysRoleService.deleteRoleByIds(ids)) {
            return AjaxResultVo.success();
        } else {
            return AjaxResultVo.error("删除失败");
        }
    }

}
